package serverStuff;

import java.util.TreeMap;
import java.util.Vector;

public class Statistics {
	class Statistic{
		public String statisticName;
		public Vector<Long> times;
		
		
		public Statistic(String name){
			times = new Vector<Long>();
			statisticName=name;
		}
		
		//Calcula a média
		public double mean(){
			double mean = 0;
			
			for (Long value : times) {
				mean+= value.doubleValue();
			}
			
			if(times.size()>0){
				mean/=times.size();
			}
			
			return mean;
		}

		//Calcula o desvio padrão.
		//Retorna um valor negativo se não 
		public double dp(){
			double meanVal,dpVal=0;
			
			if(times.size()<2){
				return -1;
			}
			
			meanVal=mean();
			
			for (Long value : times) {
				dpVal+= (value.doubleValue()-meanVal)*(value.doubleValue()-meanVal);
			}
			
			dpVal=Math.sqrt(dpVal/(times.size()-1));
			
			return dpVal;
		}
		
		
		public void printStatistics(){
			System.out.println(statisticName);
			System.out.println("Número de execuções: "+times.size());
			System.out.println("Média: "+mean());
			double dpVal=dp();
			
			System.out.print("Desvio padrão: ");
			if(dpVal<0){
				System.out.println("Dados Insuficientes");
			}else{
				System.out.println(dpVal);
			}
			System.out.println("Dados(ns):");
			
			for (Long value : times) {
				System.out.print(" "+value);
			}
			System.out.println();
		}
	}
	
	
	public TreeMap<String, Statistic> statistics;
	
	public Statistics(){
		statistics = new TreeMap<String,Statistic>();
	}
	
	public void addValue(String statisticName, long value){
		if(!statistics.containsKey(statisticName)){
			statistics.put(statisticName, new Statistic(statisticName));
		}
		statistics.get(statisticName).times.add(value);
	}
	
	public void printAll(){
		for (Statistic stat : statistics.values()) {
			stat.printStatistics();
			System.out.println();
		}
	}
	
}
